package pers.goetboy.common;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import pers.goetboy.common.exception.service.ServiceTipsException;
import pers.goetboy.common.validate.group.Update;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.util.Objects;

/**
 * controller抽象类
 * @author goetb
 */
public abstract class AbstractController<T extends AbstractEntity,M extends AbstractService<T>> {
   protected M service;
    /**
     * 取session
     *
     * @return session
     */
    protected HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 取request
     *
     * @return request
     */
    protected HttpServletRequest getRequest() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return Objects.requireNonNull(attrs).getRequest();
    }

    /**
     * 取response
     *
     * @return response
     */
    protected HttpServletResponse getResponse() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        return Objects.requireNonNull(attrs).getResponse();
    }

    /**
     * 通过id获取对象信息
     *
     * @param id id
     * @return 对象信息
     */
    @GetMapping(value = "/get/{id}")
    public T get(@PathVariable Long id) {
        return service.get(id);
    }
    /**
     * 更新对象
     *
     * @param id     id
     * @param entity 要更新得对象信息
     */
    @PutMapping(value = "/update/{id}")
    public void update(@PathVariable Long id, @RequestBody @Validated(Update.class) T entity) throws
            ServiceTipsException {
        entity.setId(id);
        service.update(entity);
    }

    /**
     * 存储对象
     *
     * @param entity 对象
     * @throws ServiceTipsException 业务异常
     */
    @PostMapping(value = "/save")
    public void save(@RequestBody T entity) throws ServiceTipsException {
        service.save(entity);
    }

    /**
     * 删除对象
     *
     * @param id id
     */
    @DeleteMapping(value = "/delete/{id}")
    public void delete(@PathVariable Long id) {
        service.delete(id);
    }

    /**
     * 更新字典状态
     *
     * @param id    id id |
     * @param state 状态 0停用|1正常
     * @throws ServiceTipsException 异常信息
     */
    @PutMapping(value = "/updateState/{id}/")
    public void updateUserState(@PathVariable Long id, @NotNull(message = "状态不能为空") @RequestParam Integer state) throws ServiceTipsException {
        service.updateState(id, EntityState.getByValue(state));
    }

}
